package com.cal.utms.report;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.cal.utms.util.ValueConvert;

/**
 * Servlet implementation class ReportCallerServlet
 */

public class ReportCallerServlet extends HttpServlet {
	private static final Map<String, String> CONTENT_TYPES = new HashMap<String, String>();

	static {
		CONTENT_TYPES.put("HTM", "text/html");
		CONTENT_TYPES.put("PDF", "application/pdf");
		CONTENT_TYPES.put("XLS", "application/vnd.ms-excel");
		CONTENT_TYPES.put("DOC", "application/msword");
		CONTENT_TYPES.put("PPT", "application/vnd.ms-powerpoint");
	}

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReportCallerServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Connection connection;
		response.setContentType("application/pdf");
		ServletOutputStream servletOutputStream = response.getOutputStream();

		String reportName = extractReportName(request.getRequestURI());
		if (reportName == null) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No report");
			return;
		}

		HashMap<String, Object> parameterMap = new HashMap<String, Object>();

		try {
			JasperDesign jasperDesign = JRXmlLoader.load(request.getServletContext().getRealPath("/reports/" + reportName + ".jrxml"));
			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

			for (JRParameter jrParameter : jasperReport.getParameters()) {
				if (!jrParameter.isSystemDefined()) {
					System.out.println(jrParameter.getValueClassName());
					parameterMap.put(jrParameter.getName(), valueConvert(jrParameter.getValueClassName(), jrParameter.getName(), request));
				}
			}
		} catch (JRException e1) {
			e1.printStackTrace();
		}

		// parameterMap.put("investment", new Integer(31));
		String reportStm = "/reports/".concat(reportName + ".jasper");
		System.out.println(reportStm);
		InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream(reportStm.toString());
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// connection =
			// DriverManager.getConnection("jdbc:mysql://10.10.10.185:3306/utmsb",
			// "root", "123");
			connection = DriverManager.getConnection("jdbc:mysql://10.10.10.110:3306/utmsb", "root", "FISFE");

			JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameterMap, connection);
			connection.close();

			servletOutputStream.flush();
			servletOutputStream.close();
		} catch (Exception e) {
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			response.setContentType("text/plain");
			response.getOutputStream().print(stringWriter.toString());
		}

	}

	private Object valueConvert(String valueClassName, String name, HttpServletRequest request) {

		String reqParamVal = request.getParameter(name);
		if (reqParamVal != null && reqParamVal.isEmpty()) {
			return null;
		}
		if (valueClassName.equals("java.lang.Integer")) {
			return ValueConvert.toInteger(reqParamVal);
		} else {
			return reqParamVal;
		}
		/*
		 * switch (valueClassName) { case "java.lang.Integer": return
		 * ValueConvert.toInteger(reqParamVal); default: return reqParamVal; }
		 */
	}

	private String extractReportName(String requestURI) {
		final int indexOfReportName = requestURI.indexOf("/ReportCallerServlet/") + 21;
		if (indexOfReportName < 0) {
			return null;
		}
		int lastIndexOfReportName = requestURI.indexOf('/', indexOfReportName);
		if (lastIndexOfReportName < indexOfReportName) {
			lastIndexOfReportName = requestURI.indexOf('?', indexOfReportName);
			if (lastIndexOfReportName < indexOfReportName) {
				lastIndexOfReportName = requestURI.length();
			}
		}

		String reportName = requestURI.substring(indexOfReportName, lastIndexOfReportName);
		return reportName;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
